using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Redis_demo.Options;
using StackExchange.Redis;

namespace Redis_demo.Extensions;

public static class ServicesCollectionExtensions
{
    public static void AddRedisOptions(this IServiceCollection services, IConfiguration config)
    {
        var temp = config.GetSection("Redis");
        services.Configure<RedisConnectOptions>(e=>config.GetSection("Redis").Bind(e));
    }

    public static void RegisterRedisConnect(this IServiceCollection services)
    {
        services.AddSingleton<IConnectionMultiplexer>(provider =>
        {
            var redisConnectOptions = provider.GetRequiredService<IOptions<RedisConnectOptions>>().Value;
            var options = new ConfigurationOptions
            {
                AbortOnConnectFail = redisConnectOptions.AbortOnConnectFail,
                ConnectTimeout = redisConnectOptions.ConnectTimeout,
                Password = redisConnectOptions.Password,
                Ssl = redisConnectOptions.Ssl,
                AllowAdmin = redisConnectOptions.AllowAdmin,
                ClientName = redisConnectOptions.ClientName,
                DefaultDatabase = redisConnectOptions.DefaultDatabase
                
            };
            options.EndPoints.Add(redisConnectOptions.Url,redisConnectOptions.Port);
            return ConnectionMultiplexer.Connect(options);
        });
    }

    public static void AddUserDbContext(this IServiceCollection services, IConfiguration config){
        services.AddDbContext<UserDbContext>(options => {
            ServerVersion serverVersion = ServerVersion.Create(Version.Parse("8.0.27"), 
                Pomelo.EntityFrameworkCore.MySql.Infrastructure.ServerType.MySql);// new ServerVersion("",ServiceLifetime.Scoped);
            options.UseMySql(config.GetConnectionString("DefaultConnection"),serverVersion);
        });
    }
}
